<?php
class Tourismorder extends CS_Controller
{
    public function _init()
    {
        $this->load->helper(array('common'));
        $this->load->library('pagination');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('express_record_model', 'express_record');
        $this->load->model('express_model', 'express');
        $this->load->model('getpwd_phone_model', 'getpwd_phone');
    }

    /**
     * 商品订单列表
     * @param number $pg
     */
    public function grid($pg=1)
    {
        $getData = $this->input->get();
        $getData['start_date'] = $this->input->get('start_date') ? $this->input->get('start_date') : date('Y-01-01', strtotime('-1 year'));
        $getData['end_date'] = $this->input->get('end_date') ? $this->input->get('end_date') : date('Y-12-31');
        if (isset($getData['excel']) && $getData['excel']== 'excel') {
            $this->excelExport($getData);
        }else{
            $page_num = 20;
            $num = ($pg - 1) * $page_num;
            $config['first_url'] = base_url('tourismorder/grid').$this->pageGetParam($this->input->get());
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('tourismorder/grid');
            $config['total_rows'] = $this->tourism_order->total($getData);
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_list'] = $this->pagination->create_links();
            $data['page_list'] = $this->tourism_order->page_list($page_num, $num, $getData);
            $data['all_rows'] = $config['total_rows'];
            $data['pg_now'] = $pg;
            $data['orderState'] = array('1'=>'未付款', '2'=>'已付款', '3'=>'已完成', '4'=>'已评价', '5'=>'已退款');
            $data['orderStatus'] = array('1'=>'取消订单', '2'=>'未付款', '3'=>'已付款', '4'=>'已发货', '5'=>'已收货', '6'=>'已评价');
            $data['order_sum'] = $this->tourism_order->order_list_sum($getData)->row();
            $data['url'] = $this->pageGetParam($this->input->get());
            $this->load->view('tourismorder/grid', $data);
        }
    }

    /**
     * @descripte   导出excel
     * @Author xiumao
     * @date 2016/6/13 0013 下午 3:54
     */
    public function excelExport($getData)
    {
        $orderStatus = array('1'=>'取消订单', '2'=>'未付款', '3'=>'已付款', '4'=>'已发货', '5'=>'已收货', '6'=>'已评价');
        $result = $this->tourism_order->excelExport($getData);
        if($result->num_rows() <= 0){
            $this->error('tourismorder/grid', null, '这个时间段没有记录');
        }
        if($result->num_rows() > 10000){
            $this->error('tourismorder/grid', null, '由于导出的数据太多，请选择一个时间范围');
        }
        $arrayOrder = $result->result_array();
        $arrayOrderDown = array();
        foreach ($arrayOrder as $key=>$item) {
            $arrayOrderDown[$key]['order_sn'] = $item['order_sn'];
            $arrayOrderDown[$key]['order_product_id'] = $item['order_product_id'];
            $arrayOrderDown[$key]['goods_attr_id'] = $item['goods_attr_id'];
            $arrayOrderDown[$key]['payer_uid'] = $item['payer_uid'];
            $arrayOrderDown[$key]['payer_name'] = $item['user_name'];
            $arrayOrderDown[$key]['goods_name'] = $item['goods_name'];
            $arrayOrderDown[$key]['attribute_value'] = $item['attribute_value'];
            $arrayOrderDown[$key]['number'] = $item['refund_num'];
            $arrayOrderDown[$key]['refund_num'] = $item['number']-$item['refund_num'];
            $arrayOrderDown[$key]['barter_num'] = $item['barter_num'];
            $arrayOrderDown[$key]['market_price'] = $item['market_price'];
            $arrayOrderDown[$key]['shop_price'] = $item['shop_price'];
            $arrayOrderDown[$key]['supply_price'] = $item['supply_price'];
            $arrayOrderDown[$key]['pay_amount'] = $item['pay_amount'];
            $arrayOrderDown[$key]['pay_total'] = bcmul($item['pay_amount'],$item['refund_num'],2);
            $arrayOrderDown[$key]['order_status'] = $orderStatus[$item['order_status']];
            $arrayOrderDown[$key]['message'] = $item['message'];
            $arrayOrderDown[$key]['created_at'] = $item['created_at'];
            $arrayOrderDown[$key]['updated_at'] = $item['updated_at'];
            $arrayOrderDown[$key]['order_note'] = $item['order_note'];
        }
        array_unshift($arrayOrderDown, array('订单编号' , '订单产品ID' , '产品ID' , '购买者账号' , '购买者' ,'产品名称','产品属性', '购买数量', '退货数量', '换货数量', '销售价','着想价','供应价', '实际应付单价','总支付价格','订单状态','用户留言' ,'创建时间', '更新时间','订单备注'));
        $this->load->library('excel');
        $this->excel->addArray($arrayOrderDown);
        $this->excel->generateXML(date('Ymd').'商城订单');
    }

    /**
     * 订单详情查看
     * @param unknown $order_id
     */
    public function edit($order_id)
    {
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            $this->error('tourismorder/grid', '', '找不到订单相关信息！');
        }
        $orderInfo = $result->row();
        $data['orderInfo'] = $result->row();
        $data['orderProductInfo'] = $this->tourism_order_product->getProductByOrderId($order_id);
        $data['tourismOrderStateArray'] = array('1'=>'未付款', '2'=>'已付款', '3'=>'已完成', '4'=>'已评价', '5'=>'已退款');
        $data['tourismOrderStatusArray'] = array( '1'=>'取消订单', '2'=>'未付款', '3'=>'已付款', '4'=>'已发货', '5'=>'已收货', '6'=>'已评价');
        $data['tourismPaymentType'] = array('1'=>'在线支付', '2'=>'货到付款');
        if ($data['orderInfo']->pay_bank) {
            $data['payMethod'] = $this->pay_method->findByBankId($orderInfo->pay_bank);
        }
        $data['profit'] = $this->tourism_order->getProfitByOrderId($order_id);
        $data['logistics'] = $this->express_record->findByNu($orderInfo->logistics);
        $data['express'] = $this->express->findByName($orderInfo->logistics_company);

        $this->load->view('tourismorder/edit', $data);
    }

    /**
     * 修改运费价格
     */
    public function modifyTransport()
    {
        $order_id = $this->input->post('order_id');
        $transport_cost = $this->input->post('transport_cost');
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            echo json_encode(array(
                'status'   => false,
                'messages' => '网络错误，订单信息不对',
            ));exit;
        }
        $orderInfo = $result->row();
        if ($transport_cost < 0) {
            echo json_encode(array(
                'status'   => false,
                'messages' => '修改价格必须要大于等于零',
            ));exit;
        }
        $is_mobile = $this->tourism_order->modifyTransport($order_id, $transport_cost);
        if ($is_mobile) {
            echo json_encode(array(
                'status'   => true,
            ));exit;
        } else {
            echo json_encode(array(
                'status'   => false,
                'messages' => '运费价格修改失败',
            ));exit;
        }
    }

     /**
     * 着想员工自己插入订单备注
     */
    public function modifyOrderNote(){

        $order_id = $this->input->post('order_id');
        $order_note = trim($this->input->post('order_note',true));
        $result = $this->tourism_order->findByOrderId($order_id);
        if($result->num_rows() <= '0'){
            echo json_encode(array(
                    'status'   => false,
                    'messages' => '网络错误，订单信息不对',
            ));exit;
        }
        $is_status = $this->tourism_order->modifyOrderNote($order_id,$order_note);
        if($is_status){
            echo json_encode(array(
                    'status'   => true,
            ));exit;
        }else{
            echo json_encode(array(
                    'status'   => false,
                    'messages' => '订单备注修改失败',
            ));exit;
        }
    }

    /**
     * 商品交易额统计
     */
    public function salesTotal()
    {
        $data['start_date'] = $this->input->get('start_date') ? $this->input->get('start_date') : date('Y-m-d 00:00:00');
        $data['end_date']   = $this->input->get('end_date') ? $this->input->get('end_date') : date('Y-m-d 23:59:59');

        $data['sales_bank_total'] = $this->tourism_order->tourismSalesBankTotal($data);
        $data['sales_count_total'] = $this->tourism_order->tourismSalesCountTotal($data)->row();
        $data['sales_refund_total'] = $this->tourism_order->tourismSalesBankRefundTotal($data, true);
        $data['sales_count_refund'] = $this->tourism_order->tourismSalesRefundTotal($data)->row();
        $data['pay_bank'] = $this->pay_method->getAllBankId(true);
        $this->load->view('tourismorder/salesTotal', $data);
    }

    /**
     * 商品销售排行榜
     */
    public function salesTourismRank($pg=1)
    {
        $page_num = 20;
        $num = ($pg-1)*$page_num;
        $config['first_url'] = base_url('tourismorder/salesTourismRank').$this->pageGetParam($this->input->get());
        $config['suffix']    = $this->pageGetParam($this->input->get());
        $config['base_url']  = base_url('tourismorder/salesTourismRank');
        $config['total_rows']  = $this->tourism_goods_base->salesTourismRankTotal($this->input->get());
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_list'] = $this->pagination->create_links();
        $data['page_list'] = $this->tourism_goods_base->salesTourismRankPageList($page_num, $num, $this->input->get());
        $data['all_rows']  = $config['total_rows'];
        $data['pg_now']    = $pg;
        $this->load->view('tourismorder/salesTourismRank', $data);
    }

    /**
     * 快递从新订阅
     * @param $order_id
     */
    public function expressRecord($order_id)
    {
        $result = $this->tourism_order->findByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            $this->error('tourismorder/edit', $order_id, '找不到订单相关信息！');
        }
        $result = $result->row();
        $company = $result->logistics_company;
        $number  = $result->logistics;
        if (!$company || !$number) {
            $this->error('tourismorder/edit', $order_id, '该订单没有快递单号，请联系管理员');
        } else {
            if (!validExpressNu($number)) {
                $this->error('tourismorder/edit', $order_id, '快递单号只能是5位以上的数字、字母组成');
            }
            $expressRecord = $this->express_record->findByNu($number);
            if ($expressRecord->num_rows() > 0) {
                $this->error('tourismorder/edit', $order_id, '快递单号已收录，无需推送');
            } else {
                $this->sendExpress($order_id, $company, $number);
            }
        }
        $this->success('tourismorder/edit', $order_id, '订阅成功！');
    }

    /**
     * 发送数据订阅
     * @param $order_id
     * @param $company
     * @param $number
     */
    public function sendExpress($order_id, $company, $number)
    {
        $this->load->library('express', null, 'expressLibrary');
        $result = $this->expressLibrary->send($company, $number);
        if ($result) {
            $express = $this->express->findByName($company)->row();
            $result = $this->express_record->insert($express->name, $company, $number);
            if (!$result) {
                $this->error('tourismorder/edit', $order_id, '推送失败(数据库插入失败)');
            }
        } else {
            $this->error('tourismorder/edit', $order_id, '推送失败('.$this->expressLibrary->getMessage().')');
        }
    }

    /**
     * @descripte   短信提醒 已付款 12小时未发货
     * @Author xiumao
     * @date 2016/6/14 0014 上午 9:53
     */
    public function sendSmsRemind()
    {
        $order_id = $this->input->post('order_id');
        $result = $this->tourism_order->findUserPhoneByOrderId($order_id);
        if ($result->num_rows() <= 0) {
            echo json_encode(array(
                'status'   => false,
                'messages' => '网络错误，订单信息不对',
            ));exit;
        }
        $orderInfo = $result->row();

        /*默认 user_detail.cellphone备用手机  备选user.mobile_phone手机号码*/
        $mobilePhone = !empty($orderInfo->cellphone) ? $orderInfo->cellphone : $orderInfo->mobile_phone;
        /*已付款状态 订单支付时间超过12小时*/
        if( $orderInfo->order_status == 3 && ( (time() - strtotime( $orderInfo->pay_time ) ) > 43200) ){
            $content1 = '尊敬的供应商'. $orderInfo->user_name .':您好,订单编号'. $orderInfo->order_sn .'的用户已提醒您发货，请尽快去发货。更多订单详情可登录后台查询。';
            $send_result = $this->getpwd_phone->selectOneSmsByPhone($mobilePhone, md5($content1));
            /*未发送短信 || (发送过短信 && 短信失效) */
            if( $send_result->num_rows()<=0 || ( $send_result->num_rows() >0 && ( time() - strtotime($send_result->row()->failtime) >0 ) ) ){
                $this->sendToSms($mobilePhone, $content1);
                $this->getpwd_phone->insertSms($orderInfo->user_name, $mobilePhone, $content1);
                echo json_encode(array(
                    'status'   => true,
                    'messages' => '发送成功',
                ));exit;
            }else{
                echo json_encode(array(
                    'status'   => false,
                    'messages' => '短信已发送,请在'. $send_result->row()->failtime .'之后再发送短信',
                ));exit;
            }
        }else{
            echo json_encode(array(
                'status'   => false,
                'messages' => '未付款，或者订单支付时间未超过12小时',
            ));exit;
        }

    }

}